#! /usr/bin/env python

# datetime helpers
#
# Copyright (C) 2011 Christian T. Steigies <steigies@physik.uni-kiel.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__author__ = "Christian T. Steigies <steigies@physik.uni-kiel.de>"
__license__ = "GPL License"

from datetime import datetime

## --------------------------------------------------------------------------
#import MySQLdb # python-mysqldb


## --------------------------------------------------------------------------
def YY(year):
    return year % 100

## --------------------------------------------------------------------------
def LastDataPoint(c,TABLE,STATION):

    querystring = "SELECT start_date_time FROM %s_%s ORDER BY start_date_time DESC LIMIT 1;" %(STATION, TABLE)
    c.execute(querystring)
    answer= c.fetchone()
    if answer == None:
        print "%s_%s is empty, you should select a --startdate. Using default date." %(STATION, TABLE)
        lastdatapoint = datetime(1910,12,31,0,0,0)
    else:
        lastdatapoint = answer[0]
    return(lastdatapoint)

## --------------------------------------------------------------------------
def ReadDataPoint(c,TABLE,STATION, dt, format="*"):

    querystring = "SELECT %s FROM %s_%s WHERE start_date_time = \"%s\";" %(format, STATION, TABLE, dt)
    #print querystring
    c.execute(querystring)
    answer= c.fetchone()
    #print answer
    return(answer)

## --------------------------------------------------------------------------
def str2datetime(s):
    if s:        
        # datetime.strptime is not available on CentOS
        #dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")

        (date, time) = s.split()
        (year, month, day) = date.split("-")
        (hour, min, sec ) = time.split(":")
        dt = datetime(int(year), int(month), int(day), int(hour), int(min), int(sec))
        
        return dt
    else:
        print "str2datetime s:", s
        raise ValueError
    
## --------------------------------------------------------------------------
def ParseDate(line):
    """parse input data
NEWK_QL_Minute.txt; yyyyy-mn-dom^hh:mm:ssTcorrTpressTuncorr; ^ = space, T = tab^M
NEWK_Minute.txt;    yyyyy-mn-dom^hh:mm:ssTcorrTpressTuncorr; ^ = space, T = tab^M

    format: yyyy-mm-dd hh:mm:ss or yyyy mm dd hh:mm:ss
            0123456789012345678"""
    
    #print "spaces:", line.count(" ")
    if (line.find(" ", 10) == 10):
        #print "SPACE found after date"
        pass
    else:
        #print "illegal data format"
        raise ValueError # SPACE not found after data

    date = line[:10]
    if (date.find("-") == 4): # after 4 digit year either -
        #print "- found after year"
        sep = "-"
    elif (date.find(" ") == 4): # or SPACE separates the month
        #print "SPACE found after year"
        sep = " "
    else:
        raise ValueError # separator not found after year

    if (date.find(sep, 5) == 7): # day is separated from month
        #print "sep found after month"
        year  = int(date.split(sep)[0])
        month = int(date.split(sep)[1])
        day   = int(date.split(sep)[2])
        pass
    else:
        raise ValueError # separator not found after month
    
        
    if (line.find(" ", 19) == 19):
        #print "SPACE found after time"
        pass
    elif (line.find("\t", 19) == 19):
        #print "TAB found after time"
        pass
    else:
        #print "illegal time format"
        raise ValueError # no SPACE or TAB found after time

    time = line[11:19]
    if (time.find(":") == 2): # after 2 digit hout either :
        #print ": found after hour"
        sep = ":"
    elif (time.find(" ") == 2): # or SPACE separates the minute
        #print "SPACE found after hour"
        sep = " "
    else:
        raise ValueError # separator not found after hour

    if (time.find(sep, 4) == 5): # second is separated from minute
        #print "sep found after minute"
        hour   = int(time.split(sep)[0])
        minute = int(time.split(sep)[1])
        second = int(time.split(sep)[2])
        pass
    else:
        raise ValueError # separator not found after month
    
    d = line[19:] # return the remaining data as-is
    # data is given as: corr press uncorr with TABs separating the fields:
    #corr = float(d.split()[0])
    #press  = float(d.split()[1])
    #uncorr   = float(d.split()[2])

    # return data in order of processing: uncorrected + pressure -> corrected
    #return(year, month, day, hour, minute, second, [uncorr, press, corr])
    return(year, month, day, hour, minute, second, d)

## --------------------------------------------------------------------------
if __name__=="__main__":
    print "This is the tools.datetool module."

    #data =["2011 10 13 21:06:00     107.43  749.30  119.85",
    #        "2011-10-30 08:50:00     94.71   759.40  95.31"]
    data = ["2011-10-30 08:50:00     94.71   759.40  95.31"]
    for line in data:
        #print ParseDate(line)
        print line
        if 0:
            (y, m, d, H, M, S, dat) = ParseDate(line)
            print "y:%i m:%i d:%i H:%i M:%i S:%i: data:%s" %(y, m, d, H, M, S, dat)
        else:
            s = line[:19]
            print s
            print str2datetime(s)
